//index.js
//获取应用实例
const app = getApp()
var md5 = require("../../utils/md5.js");
Page({
  data: {
    windowWidth: wx.getSystemInfoSync().windowWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    pixelRatio: wx.getSystemInfoSync().pixelRatio,
    hidden: false,
    setting: false,
    price_total: 0,
    lines: {},
    title: '加载中',
    openid: "",
    phone: "",
    order_id: "",
    shop_id: "",
    showModalStatus: false,
    nickName: '',
    avatarUrl: '',
    user_pone: true,
    client: '',
    total:0,
    reduceMone:0,
    reduceMone_type:false,
    hb_discount:0,//抵扣金额
    hb_amount:0,//抵扣前总额
  },

  //加载获取用户信息
  onLoad: function (option) {

     wx.showLoading({
       title: '加载数据',
     })

    var that = this;
    wx.login({
      success: function (res_code) {

      var scene = decodeURIComponent(app.globalData.wxPayShopId);
      if (scene != "undefined" && scene != "") {
       var obj_list = scene.split("client=");
       var client = obj_list[1];
          wx.request({
            url: app.globalData.erpUrl + '/web/get/shop_name',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              client: client,
            },
            success: function (res) {
              console.log(res.data.name);
              if (res.data.code == 200){
                //获取openid
                  wx.request({
                    url: app.globalData.erpUrl + '/web/get_wx_open_id',
                    header: {
                      "Content-Type": "application/x-www-form-urlencoded"
                    },
                    data: {
                      code: res_code.code,
                    },
                    success: function (res) {
                      wx.setStorageSync("open_id", res.data.openid)
                      that.setData({
                        xcx_openid: res.data.openid,
                      })
                      that.CheckXcxOpenid();
                      wx.hideLoading();
                    }
                  })
                wx.setStorageSync('shop_id', res.data.shop_id);
                that.setData({
                  shop_name: res.data.name,
                  client: client,
                  shop_id: res.data.shop_id,
                });
              }
            }
          })
        } else {
           wx.showLoading({
             title: '店铺不正确',
             icon: 'none'
           })
          // that.setData({
          //   order_id: 56,
          //   client: "mlhb1041.zntech-china.com"
          // })
        }
      }
    })
  },

  //弹窗动画
  util: function (currentStatu, type_val) {
    console.log(currentStatu);
    console.log(type_val);
    /* 动画部分 */
    // 第1步：创建动画实例   
    var animation = wx.createAnimation({
      duration: 200,  //动画时长  
      timingFunction: "linear", //线性  
      delay: 0  //0则不延迟  
    });

    // 第2步：这个动画实例赋给当前的动画实例  
    this.animation = animation;

    // 第3步：执行第一组动画  
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存  
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画  
    setTimeout(function () {
      // 执行第二组动画  
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象  
      this.setData({
        animationData: animation
      })

      //关闭  
      if (currentStatu == "close") {
        if (type_val == "user_info") {
          this.setData(
            {
              showModalStatus: false
            }
          );
        } else if (type_val == "user_pone") {
          this.setData(
            {
              showModalStatusPhone: false
            }
          );
        }
      }
    }.bind(this), 200)

    // 显示  
    if (currentStatu == "open") {
      if (type_val == "user_info") {
        this.setData(
          {
            showModalStatus: true
          }
        );
      } else if (type_val == "user_pone") {
        this.setData(
          {
            showModalStatusPhone: true
          }
        );
      }
    }
  },

  //获取用户手机号
  getPhoneNumber: function (e) {
    var that = this;
    wx.login({
      success: function (res) {
        //以下开始获取手机号
        var phone = "";
        if (e.detail.errMsg == 'getPhoneNumber:ok') {
          wx.request({
            url: 'https://mylife.zntech-china.com/web/get_wx_phone',
            header: {
              "Content-Type": "application/x-www-form-urlencoded"
            },
            data: {
              'encryptedData': e.detail.encryptedData,
              'iv': e.detail.iv,
              'code': res.code
            },
            success: function (res) {
              phone = res.data.phone.phoneNumber
              that.setData({
                phone: phone,
                user_pone: false
              });
              that.CheckXcxOpenidAndTel();
            }
          })
        } else {
          wx.showLoading({
            title: '获取手机号失败',
            icon: 'none'
          })
        }
      }
    })
  },

  /**
 * 验证并且取出用户信息
 */
  CheckXcxOpenid: function () {
    //开始验证注册用户
    var that = this;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5('User.CheckXcxOpenid' + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckXcxOpenid',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid,
            phone: result.info.reg_tel
          });
        } else {
          that.util('open', 'user_pone');
        }
      }
    })
  },

  /**
  * 验证手机号并且取出用户信息
  */
  CheckXcxOpenidAndTel: function () {
    //开始验证注册用户
    var that = this;
    var reg_tel = that.data.phone;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5(reg_tel + 'User.CheckXcxOpenidAndTel' + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckXcxOpenidAndTel',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id,
        reg_tel: reg_tel,
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid
          });
          that.util('close', 'user_pone');
        } else {
          that.util('close', 'user_pone');
          that.util('open', 'user_info');
        }
      }
    })
  },

  /**
  * 用户不存在注册新用户
  */
  CheckUserAll: function (e) {
    //开始验证注册用户
    var that = this;
    var avatar = e.detail.userInfo.avatarUrl;
    var nickName = that.replace(e.detail.userInfo.nickName);
    var sex = e.detail.userInfo.gender;
    var reg_tel = that.data.phone;
    var xcx_openid = that.data.xcx_openid;
    var shop_id = that.data.shop_id;
    var sign = md5.md5(avatar + nickName + reg_tel + 'User.CheckUserAll' + sex + shop_id + xcx_openid);
    wx.request({
      url: app.globalData.serviceUrl + 'User.CheckUserAll',
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: {
        sign: sign,
        xcx_openid: xcx_openid,
        shop_id: shop_id,
        reg_tel: reg_tel,
        sex: sex,
        nickName: nickName,
        avatar: avatar,
      },
      success: function (res) {
        var result = res.data.data;
        if (result.code == 0) {
          that.setData({
            openid: result.info.openid
          });
          that.util('close', 'user_info');
        } else {
          that.util('open', 'user_info');
        }
      }
    })
  },

  //过滤emoji表情符号
  replace: function (nickName) {
    return nickName.replace(/\uD83C[\uDF00-\uDFFF]|\uD83D[\uDC00-\uDE4F]/g, "");
  },

  getPay: function () {
    var that = this;
    var total = that.data.total;
    var hb_discount = that.data.hb_discount;
    var hb_amount = that.data.hb_amount;
    console.log(that.data.total);
    if (total != 0 ){
      // if (total.charAt(total.length - 1) == '.'){
      //   total = total+'00';
      // }
      //total = parseFloat(total);
      if (total => 0.01){
      //以下开始支付
      wx.request({
        url: app.globalData.erpUrl + '/web/under/get_pay_wx',
        header: {
          "Content-Type": "application/x-www-form-urlencoded"
        },
        data: {
          hb_discount: hb_discount,
          hb_amount: hb_amount,
          amount_total: total,
          client: that.data.client,
          phone: that.data.phone,
          open_id: wx.getStorageSync("open_id")
        },
        success: function (res) {
          console.log(res);
          if (res.data.code == -1) {
            wx.showToast({
              title: res.data.msg,
              icon: 'none',
              duration: 2000
            })
          } else {
            console.log("订单支付")
            wx.requestPayment({
              'timeStamp': res.data.data.timeStamp,
              'nonceStr': res.data.data.nonceStr,
              'package': "prepay_id=" + res.data.data.prepayId,
              'signType': 'MD5',
              'paySign': res.data.data.sign,
              'success': function (resd) {
                console.log(resd);
                console.log(that.data.title);
                wx.redirectTo({
                  url: '../result-manual/index?&shop_name=' + that.data.shop_name + '&price=' + total + '&shop_id=' + that.data.shop_id + '&order_number=' + res.data.data.order_number + '&openid=' + that.data.openid
                })
                return;
              },
              'fail': function (res) {
              }
            })
          }
        }
      })
      }else{
        wx.showToast({
          title: '支付金额不得小于1分钱',
          icon: 'none'
        })
      }
    }
  },

//字符传拼接
  butNumber:function(e){
    var that = this;
    var price_total = that.data.price_total;
      if (price_total == '0') {
        if (e.target.dataset.id == '.'){
          price_total = '0.';
        }else{
          price_total = e.target.dataset.id;
        } 
      } else {
        if (e.target.dataset.id == '.'){
          if (price_total.indexOf('.') == '-1'){
            price_total = price_total + e.target.dataset.id
          }
        }else{
          price_total = price_total + e.target.dataset.id
        }
      }
    if (price_total.length <8){
      that.setData({
        price_total: price_total
      });
      that.calculationPay(price_total, true);
    }
  },

  //删除字符串
  delNumber:function(){
    var that = this;
    var price_total = that.data.price_total;
    if (1<price_total.length){
      price_total = price_total.substr(0, price_total.length-1);
      that.setData({
        price_total: price_total
      });
      that.calculationPay(price_total,true);
    }else{
      that.setData({
        price_total: 0
      });
      that.calculationPay(0, false);
    }
  },

  calculationPay: function (price_total, reduceMone_type){
    var that = this;
    var service = 'User.GetUserDiscount';
    var reg_tel = that.data.phone;
    var shop_id = that.data.shop_id;
    var total_money = price_total;
    var sign = md5.md5(reg_tel + service + shop_id + '' + total_money);
    wx.request({
      url: app.globalData.serviceUrl + service,
      header: {
        'Content-Type': 'json'
      },
      data: {
        sign: sign,
        reg_tel: reg_tel,
        shop_id: shop_id,
        total_money: total_money
      },
      success: function (res) {
        var resulta = res.data.data.info;
        that.setData({
          hb_discount: resulta.discount,
          hb_amount: price_total,
          reduceMone_type: reduceMone_type,
          reduceMone: resulta.discount,
          total: resulta.total_money,
        })
      }
    })
  }
})
